package com.xlongwei.accounts.controller;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Param;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.handle.Result;
import org.noear.solon.validation.annotation.Min;
import org.noear.solon.validation.annotation.NotBlank;
import org.noear.solon.validation.annotation.NotNull;
import org.noear.solon.validation.annotation.Pattern;
import org.noear.solon.validation.annotation.Valid;

import com.xlongwei.accounts.dao.LedgerDao;
import com.xlongwei.accounts.model.Ledger;

import cn.dev33.satoken.annotation.SaCheckLogin;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Valid
@Controller
@SaCheckLogin
@Mapping("ledger")
public class LedgerController {
    @Inject
    LedgerDao ledgerDao;

    @Get
    @Post
    @Mapping("list")
    public Result<?> list(String type) {
        Integer userid = UserController.userid();
        List<Ledger> list = ledgerDao.list(userid);
        if (!Utils.isBlank(type)) {
            list = list.stream().filter(item -> type.equals(item.getType())).collect(Collectors.toList());
        }
        return Result.succeed(list);
    }

    @Post
    @Mapping("create")
    public Result<?> create(@Param(defaultValue = "O") @Pattern("[IOT]") String type,
            @NotBlank @Pattern(UserController.PATTERN_NAME) String name) {
        Integer userid = UserController.userid();
        List<Ledger> list = ledgerDao.list(userid);
        for (Ledger account : list) {
            if (name.equals(account.getName())) {
                return Result.failure("名称重复");
            }
        }
        Ledger ledger = new Ledger();
        ledger.setUserid(userid);
        ledger.setType(type);
        ledger.setName(name);
        Integer ledgerid = ledgerDao.create(ledger);
        ledger.setLedgerid(ledgerid);
        log.info("userid={} create ledgerid={} type={} name={}", userid, ledgerid, type, name);
        return Result.succeed(ledger);
    }

    @Post
    @Mapping("update")
    public Result<?> update(@NotNull @Min(1) Integer ledgerid,
            @NotBlank @Pattern(UserController.PATTERN_NAME) String newName)
            {
        Integer userid = UserController.userid();
        Ledger ledger = ledgerDao.retrieve(ledgerid);
        if (ledger != null && userid.equals(ledger.getUserid())
                && !Objects.equals(newName, ledger.getName())) {
            log.info("userid={} update ledgerid={} oldName={} newName={}", userid, ledgerid,
                    ledger.getName(), newName);
            ledger.setName(newName);
            ledgerDao.update(ledger);
        }
        return Result.succeed(ledger);
    }
}
